package com.lekang.le.service.impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lekang.le.mapper.RoomMapper;
import com.lekang.le.domain.Room;
import com.lekang.le.service.IRoomService;

/**
 * 房间信息Service业务层处理
 * 
 * @author szh
 * @date 2025-10-14
 */
@Service
public class RoomServiceImpl implements IRoomService 
{
    @Autowired
    private RoomMapper roomMapper;

    @Override
    public List<Room> selectRoomListWithRelations(Long floorId) {
        return roomMapper.selectRoomListWithRelations(floorId);
    }
    /**
     * 查询房间信息
     * 
     * @param id 房间信息主键
     * @return 房间信息
     */
    @Override
    public Room selectRoomById(Long id)
    {
        return roomMapper.selectRoomById(id);
    }

    /**
     * 查询房间信息列表
     * 
     * @param room 房间信息
     * @return 房间信息
     */
    @Override
    public List<Room> selectRoomList(Room room)
    {
        return roomMapper.selectRoomList(room);
    }

    /**
     * 新增房间信息
     * 
     * @param room 房间信息
     * @return 结果
     */
    @Override
    public int insertRoom(Room room)
    {
        // 验证房间号是否重复（同一楼层下）
        Room queryRoom = new Room();
        queryRoom.setRoomNo(room.getRoomNo());
        queryRoom.setFloorId(room.getFloorId());
        List<Room> existRooms = roomMapper.selectRoomList(queryRoom);
        if (!existRooms.isEmpty()) {
            throw new RuntimeException("同一楼层下房间号【" + room.getRoomNo() + "】已存在");
        }
        return roomMapper.insertRoom(room);
    }

    /**
     * 修改房间信息
     * 
     * @param room 房间信息
     * @return 结果
     */
    @Override
    public int updateRoom(Room room)
    {
        // 验证房间号是否重复（排除当前房间自身）
        Room queryRoom = new Room();
        queryRoom.setRoomNo(room.getRoomNo());
        queryRoom.setFloorId(room.getFloorId());
        List<Room> existRooms = roomMapper.selectRoomList(queryRoom);

        // 检查是否有其他房间使用相同房间号
        boolean isDuplicate = existRooms.stream()
                .anyMatch(r -> !r.getId().equals(room.getId())); // 排除自身ID

        if (isDuplicate) {
            throw new RuntimeException("同一楼层下房间号【" + room.getRoomNo() + "】已存在");
        }
        return roomMapper.updateRoom(room);
    }

    /**
     * 批量删除房间信息
     * 
     * @param ids 需要删除的房间信息主键
     * @return 结果
     */
    @Override
    public int deleteRoomByIds(Long[] ids)
    {
        return roomMapper.deleteRoomByIds(ids);
    }

    /**
     * 删除房间信息信息
     * 
     * @param id 房间信息主键
     * @return 结果
     */
    @Override
    public int deleteRoomById(Long id)
    {
        return roomMapper.deleteRoomById(id);
    }
}
